package register;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.dbutils.QueryRunner;




@WebServlet("/multiRegister.do")
@MultipartConfig(maxRequestSize=10*1024*1024)
public class multiRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String vcode = getContent(request.getPart("vcode"));
		String except = (String) request.getSession().getAttribute("vcode");
		if(!vcode.equals(except)) {
			response.sendRedirect("./register.jsp");
			return;
		}
		
		String uploadsPath = request.getServletContext().getRealPath("/uploads");
		File uploadsDir = new File(uploadsPath);
		if(!uploadsDir.exists()) {
			uploadsDir.mkdir();
		}
		
		Part file = request.getPart("userHead");
		String fileName = file.getSubmittedFileName();
		String extName = fileName.substring(fileName.lastIndexOf("."));
		String savedName = System.currentTimeMillis() + extName;		
		file.write(uploadsPath + File.separator + savedName);
		
		Part usernamePart = request.getPart("username");
		String username = getContent(usernamePart);
		
		Part pwdPart = request.getPart("password");
		String password = getContent(pwdPart);
		
		String sex = getContent(request.getPart("sex"));
		
		String interests = "";
		for(Part part : request.getParts()) {
			if(part.getName().equals("interests")) {
				interests += getContent(part) + ",";
			}
		}
	
	
//		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute("runner");
//		User user = new User(username, password, savedName, sex, interests);
//		try {
//			UserDao.register(runner, user);
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			resp.sendError(500);
//		}
// 		resp.sendRedirect("./uploads/" + savedName);
//	}
	
	private String getContent(Part part) throws IOException {
		String result = "";
		try(Scanner scanner = new Scanner(part.getInputStream())) {
			result = scanner.next();
		}	
		return result;
	}
}